B
bad member function
badbit
C
cerr
cin
clear member function
clog
cout
D
dec
E
end-of-file
eof member function
eofbit
extensibility
F
fail member function
failbit
field width
fill character
fill member function
flags member function
flush
format flags
format state
formatted input/output
fstream
G
gcount
get member function
getline
good member function
H
hex
I
ifstream
ignore
iomanip.h
ios base class
ios::adjustfield
ios::basefield
ios::fixed
ios::floatfield
ios::internal
ios::scientific
ios::scientific flag
ios::showbase
ios::showpoint
ios::showpos
iostream
istream class
L
leading 0
leading 0x or leading 0X
left
left justify
O
oct
ofstream
operator void* member function
operator! member function
ostream class
P
padding
parameterized stream manipulator
peek
precision member function
put member function
putback
R
rdstate member function
read
resetiosflags stream manipulator
right justification
S
setbase
setf member function
setfill manipulator
setiosflags
setprecision
setw
skipws
stream input
stream output
stream-extraction operator (>>)
stream-insertion operator (<<)
T
tie
type-safe I/O
U
unformatted I/O
unsetf member function
uppercase
W
whitespace
width
write member function
ws stream manipulator

When prompting the user on how to end input from the keyboard, ask the user to "enter end-of-file to end input" rather than prompting for <ctrl>-d (UNIX and Macintosh) or <ctrl>-z (PC and VAX).
Consciousness ... does not appear to itself chopped up in bits ... A "river" or a "stream" are the metaphors by

which it is most naturally described.
William James

All the news that's fit to print.
Adolph S. Ochs

Fig. 11.1 Portion of the stream I/O class hierarchy.
Fig. 11.2 Portion of stream-I/O class hierarchy with key file-processing classes.
Fig. 11.3 Outputting a string using stream insertion.
Fig. 11.4 Outputting a string using two stream insertions.
Fig. 11.5 Using the endl stream manipulator.
Fig. 11.6 Outputting expression values.
Fig. 11.7 Cascading the overloaded << operator.
Fig. 11.8 Printing the address stored in a char * variable.
Fig. 11.9 Calculating the sum of two integers input from the keyboard with cin and the stream-extraction operator.
Fig. 11.10 Avoiding a precedence problem between the stream-insertion operator and the conditional operator.
Fig. 11.11 Stream-extraction operator returning false on end-of-file.
Fig. 11.12 Using member functions get, put, and eof.
Fig. 11.13 Contrasting input of a string using cin with stream extraction and input with cin.get.
Fig. 11.14 Character input with member function getline.
Fig. 11.15 Unformatted I/O with the read, gcount and write member functions.
Fig. 11.16 Using the hex, oct, dec and setbase stream manipulators.
Fig. 11.17 Controlling precision of floating-point values.
Fig. 11.18 Demonstrating the width member function.
Fig. 11.19 Creating and testing user-defined, nonparameterized stream manipulators.
Fig. 11.20 Format state flags.
Fig. 11.21 Controlling the printing of trailing zeros and decimal points with float values.
Fig. 11.22 Left-justification and right-justification.
Fig. 11.23 Printing an integer with internal spacing and forcing the plus sign.
Fig. 11.24 Using the fill member function and the setfill manipulator to change the padding character for fields larger than the values being printed.
Fig. 11.25 Using the ios::showbase flag.
Fig. 11.26 Displaying floating-point values in system default, scientific, and fixed formats.
Fig. 11.27 Using the ios::uppercase flag.
Fig. 11.28 Demonstrating the flags member function.
Fig. 11.29 Testing error states.

Figure 11.1 - Portion of the stream I/O class hierarchy.
Figure 11.2 - Portion of stream-I/O class hierarchy with key file-processing classes.

Figure 11.20 - Format state flags. (Part 1 of 2)
Figure 11.20 - Format state flags. (Part 2 of 2)
Answers 11.1

a) friend

b) ios::left, ios::right, and ios::internal.

c) streams.

d) setiosflags, resetiosflags.

e) iostream.h.

f) setf, unsetf.

g) strstream.h

h) iomanip.h.

i) fstream.h.

j) endl.


k) stdiostream.h.  


l) write.  

m) istream.

n) cerr or clog.

o) ostream.

p) <<.

q) cin, cout, cerr, and clog.

r) >>.

s) oct, hex, dec.

t) six digits of precision.

u) ios::showpos.

Answers 11.2
a) True.
b) False. The stream-insertion and stream-extraction operators are not overloaded for all user-defined types. The programmer of a class must specifically provide the overloaded operator functions to overload the stream operators for use with each user-defined type.
c) False. The stream member function flags() with no arguments simply returns the current value of the flags state variable.
d) True.
e) True.
f) False. To overload the stream-insertion operator <<, the overloaded operator function must take an ostream reference and a reference to a user-defined type as arguments, and return an ostream reference.
g) True. Unless ios::skipws is off.
h) False. The I/O features of C++ are provided as part of the C++ Standard Library. The C++ language does not contain capabilities for input, output, or file processing.
i) True.
j) True.
k) True.
m) True.
n) True.
o) True.
p) False. The ostream member function put outputs its single character argument.
q) False. The stream manipulators dec, oct, and hex set the output format state for integers to the specified base until the base is changed again or the program terminates.
r) False. Memory addresses are displayed in hexadecimal format by default. To display addresses as long integers, the address must be cast to a long value.

Answers 11.3

a)  cout << "Enter your name: ";

b) cout.setf(ios::uppercase);

c) cout << (void *) string;

d) cout.setf(ios::scientific, ios::floatfield);

e) cout << integerPtr;

f) cout << setiosflags(ios::showbase);

g) cout << *floatPtr;

h) cout.fill( '*' );

cout << setfill( '*' );

i) cout.put( 'O' ).put( 'K' );


j)  cin.peek();


k)  c = cin.get()

cin.get( c );

l) cin.ignore( 6 );

m) cin.read( line, 50 );

n) cin.get( name, 10, '.' );

cin.getline( name, 10, '.' );

o) cout.write( line, cin.gcount() );

p) cout.flush();

cout << flush;

q) cout << 124 << 18.376 << 'Z' << 1000000 << "String";


r)  cout << cout.precision();


s)  cin >> months >> percentageRate;

t) cout << setprecision( 3 ) << 1.92 << '\ '

<< 1.925 << '\ ' << 1.9258;

u) cout << oct << 100 << hex << 100 << dec << 100;

v) cout << 100 << setbase( 8 ) << 100 << setbase( 16 ) << 100;

w) cout << setw( 10 ) << 1234;

x) cin.get( line, 20, 'z' );

y) cout << setw( x ) << setprecision( y ) << 87.4573;


Answer 11.4
a) Error: The precedence of the << operator is higher than the precedence of <= which causes the statement to be evaluated improperly and causes a compiler error.
Correction: To correct the statement, add parentheses around the expression x <= y. This problem will occur with any expression that uses operators of lower precedence than the << operator if the expression is not placed in parentheses.
b) Error: In C++, characters are not treated as small integers as they are in C.
Correction: To print the numerical value for a character in the computer's character set, the character must be cast to an integer value as in the following:

cout << int('c');

c) Error: Quote characters cannot be printed in a string unless an escape sequence is used.
Correction: Print the string in one of the following ways:

cout << '"' << "A string in quotes" << '"';

cout << "\\"A string in quotes\\"";


Anwers 11.5

a)  12345

**123

123

b) $$$$$10000

c) 1024.988

d) 0143

0x63

e) 100000

+100000

f) 4.45e+02

Answer 11.7
The solution to this exercise can be found on your Cyber Classroom CD. Copy the file cpphtp2/answers/P11_07.zip to your hard drive and unzip the program code.

Answer 11.9
The solution to this exercise can be found on your Cyber Classroom CD. Copy the file cpphtp2/answers/P11_09.zip to your hard drive and unzip the program code.

Answer 11.10
The solution to this exercise can be found on your Cyber Classroom CD. Copy the file cpphtp2/answers/P11_10.zip to your hard drive and unzip the program code.

Answer 11.12
The solution to this exercise can be found on your Cyber Classroom CD. Copy the file cpphtp2/answers/P11_12.zip to your hard drive and unzip the program code.

Answer 11.15
The solution to this exercise can be found on your Cyber Classroom CD. Copy the file cpphtp2/answers/P11_15.zip to your hard drive and unzip the program code.

Answer 11.18
The solution to this exercise can be found on your Cyber Classroom CD. Copy the file cpphtp2/answers/P11_18.zip to your hard drive and unzip the program code.

Exercise 11.1
Answer each of the following:
a) Overloaded stream operators are often defined as ________ functions of a class.
b) The format justification bits that can be set include ________, _________, and

________.
c) Input/output in C++ occurs as _________ of bytes.
d) Parameterized stream manipulators ________ and ________ can be used to set and reset format state flags.
e) Most C++ programs should include the _________ header file that contains basic information required for all stream I/O operations.
f) Member functions _______ and ______ are used to set and reset format state flags.
g) Header file _________ contains information for performing "in-memory" formatting.
h) When using parameterized manipulators, the header file ________ must be included.
i) Header file ________ contains information for user controlled file processing.
j) The ________ stream manipulator inserts a newline character in the output stream and flushes the output stream.
k) Header file ________ is used in programs that mix C-style and C++-style I/ O.
l) The ostream member function ________ is used to perform unformatted output.
m) Input operations are supported by the ________ class.
n) Outputs to the standard error stream are directed to either the ________ or the

________ stream object.
o) Output operations are supported by the ________ class.
p) The symbol for the stream-insertion operator is ________.
q) The four objects that correspond to the standard devices on the system include

________, ________, ________, and ________.
r) The symbol for the stream-extraction operator is ________.
s) The stream manipulators ________, ________, and ________ are used to specify that integers should be displayed in octal, hexadecimal, and decimal formats.
t) The default precision for displaying floating-point values is ________.
u) When set, the ________ flag causes positive numbers to display with a plus sign.

Exercise 11.2
State whether the following are true or false. If the answer is false, explain why.
a) The stream member function flags() with a long argument sets the flags state variable to its argument and returns its previous value.
b) The stream-insertion operator << and the stream-extraction operator >> are overloaded to handle all standard data types--including strings and memory addresses (stream-insertion only)--and all user-defined data types.
c) The stream member function flags() with no arguments resets all the flag bits in the flags state variable.
d) The stream-extraction operator >> can be overloaded with an operator function that takes an istream reference and a reference to a user-defined type as arguments and returns an istream reference.
e) The ws stream manipulator skips leading whitespace in an input stream.
f) The stream-insertion operator << can be overloaded with an operator function that takes an istream reference and a reference to a user-defined type as arguments and returns an istream reference.
g) Input with the stream-extraction operator >> always skips leading whitespace characters in the input stream.
h) The input and output features are provided as part of C++.
i) The stream member function rdstate() returns the state of the current stream.
j) The cout stream is normally connected to the display screen.
k) The stream member function good() returns true if the bad(), fail(), and eof() member functions all return false.
l) The cin stream is normally connected to the display screen.
m) If a nonrecoverable error occurs during a stream operation, the bad member function will return true.
n) Output to cerr is unbuffered and output to clog is buffered.
o) When the ios::showpoint flag is set, floating-point values are forced to print with the default six digits of precision--provided that the precision value has not been changed, in which case floating-point values print with the specified precision.
p) The ostream member function put outputs the specified number of characters.
q) The stream manipulators dec, oct, and hex only affect the next integer output operation.
r) When output, memory addresses are displayed as long integers by default.
Exercise 11.3
For each of the following, write a single statement that performs the indicated task.
a) Output the string "Enter your name: ".
b) Set a flag to cause the exponent in scientific notation and the letters in hexadecimal values to print in capital letters.
c) Output the address of the variable string of type char *.
d) Set a flag so that floating-point values print in scientific notation.
e) Output the address of the variable integerPtr of type int *.
f) Set a flag so that when integer values are output the integer base for octal and hexadecimal values is displayed.
g) Output the value pointed to by floatPtr of type float *.
h) Use a stream member function to set the fill character to '*' for printing in field widths larger than the values being output. Write a separate statement to do this with a stream manipulator.
i) Output the characters 'O' and 'K' in one statement with ostream function put.
j) Get the next character in the input stream without extracting it from the stream.
k) Input a single character into variable c of type char using the istream member function get in two different ways.
l) Input and discard the next six characters in the input stream.
m) Use the istream member function read to input 50 characters into array line of type char.
n) Read 10 characters into character array name. Stop reading characters if the '.' delimiter is encountered. Do not remove the delimiter from the input stream. Write another statement that performs this task and removes the delimiter from the input.
o) Use the istream member function gcount to determine the number of characters input into character array line by the last call to istream member function read and output that number of characters using ostream member function write.
p) Write separate statements to flush the output stream using a member function and a stream manipulator.
q) Output the following values: 124, 18.376, 'Z', 1000000, and "String".
r) Print the current precision setting using a member function.
s) Input an integer value into int variable months and a floating-point value into float variable percentageRate.
t) Print 1.92, 1.925, and 1.9258 with 3 digits of precision using a manipulator.
u) Print integer 100 in octal, hexadecimal, and decimal using stream manipulators.
v) Print integer 100 in decimal, octal, and hexadecimal using a single stream manipulator to change the base.
w) Print 1234 right-justified in a 10 digit field.
x) Read characters into character array line until the character 'z' is encountered up to a limit of 20 characters (including a terminating null character). Do not extract the delimiter character from the stream.
y) Use integer variables x and y to specify the field width and precision used to display the double value 87.4573 and display the value.

Exercise 11.4
Identify the error in each of the following statements and explain how to correct it.

a)  cout << "Value of x <= y is: " << x <= y;

b) The following statement should print the integer value of ' c'.

cout << 'c';

c) cout << ""A string in quotes"";


Exercise 11.5
For each of the following, show the output.

a)  cout << "12345" << endl;

cout.width( 5 );

cout.fill( '*' );

cout << 123 << endl << 123;

b) cout << setw( 10 ) << setfill( '$' ) << 10000;

c) cout << setw( 8 ) << setprecision( 3 ) << 1024.987654;

d) cout << setiosflags( ios::showbase ) << oct << 99

<< endl << hex << 99;



e)  cout << 100000 << endl


         << setiosflags( ios::showpos ) << 100000;

f) cout << setw( 10 ) << setprecision( 2 ) <<

<< setiosflags( ios::scientific ) << 444.93738;


Exercise 11.6
Write a statement for each of the following:
a) Print integer 40000 left-justified in a 15-digit field.
b) Read a string into character array variable state.
c) Print 200 with and without a sign.
d) Print the decimal value 100 in hexadecimal form preceded by 0x.
e) Read characters into array s until the character 'p' is encountered up to a limit of 10 characters (including the terminating null character). Extract the delimiter from the input stream and discard it.
f) Print 1.234 in a 9-digit field with preceding zeros.
g) Read a string of the form "characters" from the standard input. Store the string in character array s. Eliminate the quotation marks from the input stream. Read a maximum of 50 characters (including the terminating null character).

Exercise 11.7
Write a program to test inputting integer values in decimal, octal, and hexadecimal format. Output each integer read by the program in all three formats. Test the program with the following input data: 10, 010, 0x10.

Exercise 11.8
Write a program that prints pointer values using casts to all the integer data types. Which ones print strange values? Which ones cause errors?

Exercise 11.9
Write a program to test the results of printing the integer value 12345 and the floating-point value 1.2345 in various size fields. What happens when the values are printed in fields containing fewer digits than the values?

Exercise 11.10
Write a program that prints the value 100.453627 rounded to the nearest digit, tenth, hundredth, thousandth, and ten thousandth.

Exercise 11.11
Write a program that inputs a string from the keyboard and determines the length of the string. Print the string using twice the length as the field width.

Exercise11.12
Write a program that converts integer Fahrenheit temperatures from 0 to 212 degrees to floating-point Celsius temperatures with 3 digits of precision. Use the formula

celsius = 5.0 / 9.0 * ( fahrenheit - 32 );

to perform the calculation. The output should be printed in two right-justified columns, and the Celsius temperatures should be preceded by a sign for both positive and negative values.

Exercise 11.13
In some programming languages, strings are entered surrounded by either single or double quotation marks. Write a program that reads the three strings suzy, "suzy", and 'suzy'. Are the single and double quotes ignored or read as part of the string?

Exercise 11.14
In Fig. 8.3, the stream-extraction and -insertion operators were overloaded for input and output of objects of the PhoneNumber class. Rewrite the stream- extraction operator to perform the following error checking on input. The operator>> function will need to be entirely recoded.
a) Input the entire phone number into an array. Test that the proper number of characters have been entered. There should be a total of 14 characters read for a phone number of the form (800) 555-1212. Use the stream member function clear to set ios::failbit for improper input.
b) The area code and exchange do not begin with 0 or 1. Test the first digit of the area code and exchange portions of the phone number to be sure that neither
begins with 0 or 1. Use stream member function clear to set ios::failbit for improper input.
c) The middle digit of an area code used to always be 0 or 1 (although this has changed recently). Test the middle digit for a value of 0 or 1. Use the stream member function clear to set ios::failbit for improper input. If none of the above operations results inios::failbit being set for improper input, copy the three parts of the telephone number into the areaCode, exchange, and line members of the PhoneNumber object. In the main program, if ios::failbit has been set on the input, have the program print an error message and end rather than print the phone number.

Exercise 11.15
Write a program that accomplishes each of the following:
a) Create the user-defined class Point that contains the private integer data members xCoordinate and yCoordinate, and declares stream-insertion and stream-extraction overloaded operator functions as friends of the class.
b) Define the stream-insertion and stream-extraction operator functions. The stream-extraction operator function should determine if the data entered is valid data, and if not, it should set the ios::failbit to indicate improper input. The stream-insertion operator should not be able to display the point after an input error occurred.
c) Write a main function that tests input and output of user-defined class Point using the overloaded stream-extraction and stream-insertion operators.
Exercise 11.16
Write a program that accomplishes each of the following:
a) Create the user-defined class Complex that contains the private integer data members real and imaginary, and declares stream-insertion and stream- extraction overloaded operator functions as friends of the class.
b) Define the stream-insertion and -extraction operator functions. The stream- extraction operator function should determine if the data entered is valid, and if not, it should set ios::failbit to indicate improper input. The input should be of the form:

3 + 8i

c) The values can be negative or positive, and it is possible that one of the two values is not provided. If a value is not provided, the appropriate data member
should be set to 0. The stream-insertion operator should not be able to display the point if an input error occurred. The output format should be identical to the input format shown above. For negative imaginary values, a minus sign should be printed rather than a plus sign.
d) Write a main function that tests input and output of user-defined class Complex using the overloaded stream-extraction and stream-insertion operators.

Exercise 11.17
Write a program that uses a for structure to print a table of ASCII values for the characters in the ASCII character set from 33 to 126. The program should print the decimal value, octal value, hexadecimal value, and character value for each character. Use the stream manipulators dec, oct, and hex to print the integer values.

Exercise 11.18
Write a program to show that the getline and three-argument get istream member functions each end the input string with a string terminating null character. Also show that get leaves the delimiter character on the input stream while getline extracts the delimiter character and discards it. What happens to the unread characters in the stream?

Exercise 11.19
Write a program that creates the user-defined manipulator skipwhite to skip leading whitespace characters in the input stream. The manipulator should use the isspace function from the ctype.h library to test if the character is a whitespace character. Each character should be input using the istream member function get. When a non-whitespace character is encountered, the skipwhite manipulator finishes its job by placing the character back on the input stream and returning an istream reference.
Test the manipulator by creating a main function in which the ios::skipws flag is unset so that the stream-extraction operator does not automatically skip whitespace. Then test the manipulator on the input stream by entering a
character preceded by whitespace as input. Print the character that was input to confirm that a whitespace character was not input.

Figure 11.3 Outputting a string using stream insertion.



Figure 11.4 Outputting a string using two stream insertions.



Figure 11.5 Using the endl stream manipulator.



Figure 11.6 Outputting expression values.



Figure 11.7 Cascading the overloaded << operator.



Figure 11.8 Printing the address stored in a char * variable.



Figure 11.9 Calculating the sum of two integers input from the keyboard with cin and the stream-extraction operator.



Figure 11.10 Avoiding a precedence problem between the stream-insertion operator and the conditional operator.



Figure 11.11 Stream-extraction operator returning false on end-of-file.



Figure 11.12 Using member functions get, put, and eof.



Figure 11.13 Contrasting input of a string using cin with stream extraction and input with cin.get.



Figure 11.14 Character input with member function getline.



Figure 11.15 Unformatted I/O with the read, gcount and write member functions.



Figure 11.16 Using the hex, oct, dec and setbase stream manipulators.



Figure 11.17 Controlling precision of floating-point values.



Figure 11.18 Demonstrating the width member function.



Figure 11.19 Creating and testing user-defined, nonparameterized stream manipulators.



Figure 11.21 Controlling the printing of trailing zeros and decimal points with float values.



Figure 11.22 Left-justification and right-justification.



Figure 11.23 Printing an integer with internal spacing and forcing the plus sign.



Figure 11.24 Using the fill member function and the setfill manipulator to change the padding character for fields larger than the values being printed.



Figure 11.25 Using the ios::showbase flag.



Figure 11.26 Displaying floating-point values in system default, scientific, and fixed formats.



Figure 11.27 Using the ios::uppercase flag.



Figure 11.28 Demonstrating the flags member function.



Figure 11.29 Testing error states.



Use unformatted I/O for the best performance in high- volume file processing.

Use the C++ form of I/ O exclusively in C++ programs, despite the fact that C-style I/O is available to C++ programmers.

When outputting expressions, place them in parentheses to prevent operator precedence problems between the operators in the expression and the << operator.

* To understand how to use C++ object-oriented stream input/output. * To be able to format inputs and outputs. * To understand the stream I/O class hierarchy. * To understand how to input/output objects of user-defined types. * To be able to create user-defined stream manipulators. * To be able to determine the success or failure of input/output operations. * To be able to tie output streams to input streams.
Attempting to read from an ostream (or from any other output- only stream).

Attempting to write to an istream (or to any other input-only stream).

Not providing parentheses to force proper precedence when using the relatively high precedence stream- insertion operator << or stream-extraction operator >>.
The width setting applies only for the next insertion or extraction; afterward, the width is implicitly set to 0, i.e., output values will simply be as wide as they need to be. The width function with no argument
returns the current setting. It is a logic error to assume that the width setting applies to all outputs.

When not providing a sufficiently wide field to handle outputs, the outputs print as wide as they need to be, possibly causing difficult-to-read outputs.

C++ style I/O is type safe.

C++ enables a common treatment of I/O of predefined types and user-defined types. This kind of commonality facilitates software development in general and software reuse in particular.

11 C++ Stream Input/Output
11.1Introduction
11.2Streams
11.3Stream Output
11.4Stream Input
11.5Unformatted I/O with read, gcount and write
11.6Stream Manipulators
11.7Stream Format States
11.8Stream Error States
11.9Tying an Output Stream to an Input Stream
11.10Summary
Terminology
Figures
11.1 Introduction
The C++ standard libraries provide an extensive set of input/output capabilities. This chapter discusses a range of capabilities sufficient for performing most common I/O operations and overviews the remaining capabilities. Some of the features presented here were discussed earlier in the text, but this chapter provides a more complete discussion of the input/output capabilities of C++.
Many of the I/O features described here are object- oriented. The reader should find it interesting to see how such capabilities are implemented. This style of I/
O makes use of other C++ features such as references, function overloading, and operator overloading.
As we will see, C++ uses type safe I/O. Each I/O operation is automatically performed in a manner sensitive to the data type. If an I/O function has been properly defined to handle a particular data type, then that function is automatically called to handle that data type. If there is no match between the type of the actual data and a function for handling that data type, a compiler error indication is set. Thus, improper data cannot sneak through the system (as can occur in C--a hole in C that allows for some rather subtle and often bizarre errors).
Users may specify I/O of user-defined types as well as standard types. This extensibility is one of the most valuable features of C++.
11.2 Streams
C++ I/O occurs in streams of bytes. A stream is simply a sequence of bytes. In input operations, the bytes flow from a device (e.g., a keyboard, a disk drive, a network connection) to main memory. In output operations, bytes flow from main memory to a device (e.g., a display screen, a printer, a disk drive, a network connection).
The application associates meaning with bytes. The bytes may represent ASCII characters, internal format raw data, graphics images, digital speech, digital video
or any other kind of information an application may require.
The job of the system I/O mechanisms is to move bytes from devices to memory and vice versa in a consistent and reliable manner. Such transfers often involve mechanical motion such as the rotation of a disk or a tape, or typing keystrokes at a keyboard. The time these transfers take is normally huge compared to the time the processor takes to manipulate data internally. Thus, I/O operations require careful planning and tuning to ensure maximum performance. Issues like this are discussed in depth in operating systems textbooks (De90).
C++ provides both "low-level" and "high-level" I/O capabilities. Low-level I/O capabilities (i.e., unformatted I/O) typically specify that some number of bytes should simply be transferred device-to-memory or memory-to-device. In such transfers, the individual byte is the item of interest. Such low-level capabilities do provide high-speed, high-volume transfers, but these capabilities are not particularly convenient for people.
People prefer a higher-level view of I/O, i.e., formatted I/O, in which bytes are grouped into meaningful units such as integers, floating-point numbers, characters, strings and user-defined types. These type-oriented
capabilities are satisfactory for most I/O other than high-volume file processing.
Drag the correct term to the box associated with the attribute:

Sequence of bytes.
Unformatted, byte-based input/output.
Formatted, data-type oriented input/output.
11.2.1 Iostream Library Header Files
The C++ iostream library provides hundreds of I/O capabilities. Several header files contain portions of the library interface.
Most C++ programs include the <iostream.h> header file which contains basic information required for all stream-I/O operations. The <iostream.h> header file contains the cin, cout, cerr, and clog objects which correspond to the standard input stream, standard output stream, the unbuffered standard error stream, and the buffered standard error stream. Both unformatted- and formatted-I/O capabilities are provided.
The <iomanip.h> header contains information useful for performing formatted I/O with so-called parameterized stream manipulators.
The <fstream.h> header contains information important for user-controlled file processing operations. We use this header in the file processing programs of Chapter 13.
Each C++ implementation generally contains other I/O- related libraries that provide system-specific capabilities such as controlling special-purpose devices for audio and video I/O.
Select the true statement(s).
Header <fstream.h> provides I/O formatting capabilities.
clog is an object representing a buffered error stream.
The header <iomanip.h> contains parameterized stream manipulators.
11.2.2 Stream Input/Output Classes and Objects
The iostream library contains many classes for handling a wide variety of I/O operations. The istream class supports stream-input operations. The ostream class supports stream-output operations. The iostream class supports both stream-input and stream-output operations.
The istream class and the ostream class are each derived through single inheritance from the ios base class. The iostream class is derived through multiple inheritance from both the istream class and the ostream class. These inheritance relationships are summarized in Fig. 11.1.
Operator overloading provides a convenient notation for performing input/output. The left shift operator (<<) is overloaded to designate stream output and is referred to as the stream-insertion operator. The right shift operator (>>) is overloaded to designate stream input and is referred to as the stream-extraction operator. These operators are used with the standard stream objects cin, cout, cerr, and clog, and commonly with user-defined stream objects.
cin is an object of the istream class and is said to be "tied to" (or connected to) the standard input device, normally the keyboard. The stream-extraction operator as used in the following statement causes a value for
integer variable grade (assuming grade has been declared as int) to be input from cin to memory:

cin >> grade;

Note that the stream-extraction operation is "smart enough" to "know" what the type of the data is. Assuming that grade has been properly declared, no additional type information needs to be specified for use with the stream-extraction operator (as is the case, incidentally, in C-style I/O).
cout is an object of the ostream class and is said to be "tied to" the standard output device, normally the display screen. The stream-insertion operator as used in the following statement causes the value of integer
variable grade to be output from memory to the standard output device:

cout << grade;

Note that the stream-insertion operator is "smart enough" to "know" the type of grade (assuming it has been properly declared), so no additional type information needs to be specified for use with the stream-insertion operator.
cerr is an object of the ostream class and is said to be "tied to" the standard error device. Outputs to object cerr are unbuffered. This means that each stream insertion to cerr causes its output to appear
immediately; this is appropriate for promptly notifying a user about errors.
clog is an object of the ostream class and is also said to be "tied to" the standard error device. Outputs to clog are buffered. This means that each insertion to clog could cause its output to be held in a buffer until the buffer is filled or until the buffer is flushed.
C++ file processing uses the classes ifstream to perform file input operations, ofstream for file output operations, and fstream for file input/output operations. The ifstream class inherits from istream, the ofstream class inherits from ostream, and the fstream class inherits from iostream. The various inheritance
relationships of the I/O-related classes are summarized in Fig. 11.2. There are many more classes in the full stream-I/O class hierarchy supported at most installations, but the classes shown here provide the vast majority of the capabilities most programmers will need. See the class library reference for your C++ system for more file processing information.
Drag the correct term to the box associated with the attribute:

Data type for file output.
Base class of istream.
Data type for both file output and file input.
Class type for cerr and clog.
File input operations.
Stream input operations.
11.3 Stream Output
The C++ ostream class provides the ability to perform formatted and unformatted output. Capabilities for output include: output of standard data types with the stream-insertion operator; output of characters with the put member function; unformatted output with the write member function (Section 11.5); output of integers in decimal, octal and hexadecimal formats (Section 11.6.1); output of floating-point values with various precisions (Section 11.6.2), with forced decimal points (Section 11.7.2), in scientific notation and in fixed notation (Section 11.7.6); output of data justified
in fields of designated field widths (Section 11.7.3); output of data in fields padded with specified characters (Section 11.7.4); and output of uppercase letters in scientific notation and hexadecimal notation (Section 11.7.7).
11.3.1 Stream-Insertion Operator
Stream output may be performed with the stream- insertion operator, i.e., the overloaded << operator. The << operator is overloaded to output data items of built- in types, to output strings and to output pointer values. Section 11.9 shows how to overload << to output data items of user-defined types. Figure 11.3 demonstrates output of a string using a single stream-insertion statement. Multiple insertion statements may be used as in Fig. 11.4. When this program is run, it produces the same output as the previous program.
The effect of the \n (newline) escape sequence is also achieved by the endl (end line) stream manipulator, as
in Fig. 11.5. The endl stream manipulator issues a newline character and, in addition, flushes the output buffer (i.e., causes the output buffer to be output immediately even if it is not full). The output buffer may also be flushed simply by

cout << flush;

Stream manipulators are discussed in detail in Section 11.6.
Expressions can be output as shown in Fig. 11.6.
Select the statement that is equivalent to

cout << "Hello" << endl;.
cout << "Hello\n";.
cout << "Hello\n\n";.
cout << "Hello\n" << flush.
cout << "Hello" << flush.
Operators 11.3.2 Cascading Stream-Insertion/Extraction Operators
The overloaded << and >> operators may each be used in a cascaded form as shown in Fig. 11.7.
The multiple stream insertions in Fig. 11.7 are executed as if they had been written:

( ( ( cout << "47 plus 53 is " ) 

<< ( 47 + 53 ) ) << endl );

i.e., << associates from left to right. This kind of cascading of stream-insertion operators is allowed because the overloaded << operator returns a reference to its left-operand object, i.e., cout. Thus the leftmost parenthesized expression

( cout << "47 plus 53 is " )

outputs the specified character string and returns a reference to cout. This allows the middle parenthesized expression to be evaluated as

( cout << ( 47 + 53 ) )

which outputs the integer value 100 and returns a reference to cout. The rightmost parenthesized expression is then evaluated as

cout << endl

which outputs a newline, flushes cout, and returns a reference to cout. This last return is not used.
Select the statement that results in a syntax error.
cout << ( a + b / 8 );.
cout << ( ( x ) );.
cout << "Hello" << ' ' << endl.
cout << z += 22;.
11.3.3 Output of char * Variables
In C-style I/O, it is necessary for the programmer to supply type information. C++ determines data types automatically--a nice improvement over C. But sometimes this "gets in the way." For example, we know that a character string is of type char *. Suppose we want to print the value of that pointer, i.e., the memory address of the first character of that string. But the << operator has been overloaded to print data of type char * as a null-terminated string. The solution is to cast the pointer to void * (this should be done to any pointer variable the programmer wishes to output as an address). Figure 11.8 demonstrates printing a char *
variable in both string and address formats. Note that the address prints as a hexadecimal (base 16) number. Hexadecimal numbers in C++ begin with 0x or 0X. We say more about controlling the bases of numbers in Sections 11.6.1, 11.7.4, 11.7.5 and 11.7.7.
Select the statement that outputs the address pointed to by char *ptr.
cout << *ptr;.
cout << static_cast< void * >( ptr );.
cout << static_cast< void * >( *ptr );.
cout << ptr;.
put; Cascading puts 11.3.4 Character Output with Member Function put; Cascading puts
The put member function outputs one character as in

cout.put( 'A' );

which displays A on the screen. Calls to put may be cascaded as in

cout.put( 'A' ).put( '\n' );

which outputs the letter A followed by a newline character. As with <<, the preceding statement executes in this manner because the dot operator (.) associates from left to right and the put member function returns a reference to the object through which the put call is
invoked. The put function may also be called with an ASCII-valued expression, as in cout.put( 65 ) which also outputs A.
Select the statement that generates a syntax error.
cout.put( 'x' );.
cout.put( "Hello" );.
cout.put( '\n' );.
cout.put( 'a' ).put( 'b' );.
11.4 Stream Input
Now let us consider stream input. This may be performed with the stream-extraction operator, i.e., the overloaded >> operator. This operator normally skips whitespace characters (such as blanks, tabs, and newlines) in the input stream. Later we will see how to change this behavior. The stream-extraction operator returns zero (false) when end-of-file is encountered on a stream; otherwise, the stream-extraction operator returns a reference to the object through which it is invoked. Each stream contains a set of state bits used to control the state of the stream (i.e., formatting, setting
error states, etc.). Stream extraction causes the stream's failbit to be set if data of the wrong type is input, and causes the stream's badbit to be set if the operation fails. We will soon see how to test these bits after an I/O operation. Sections 11.7 and 11.8 discuss the stream state bits in detail.
11.4.1 Stream-Extraction Operator
To read two integers, use the cin object and the overloaded >> stream-extraction operator as in Fig. 11.9. Note that stream-extraction operations can also be cascaded.
The relatively high precedence of the >> and << operators can cause problems. For example, the program of Fig. 11.10 will not compile properly without the parentheses around the conditional expression. The reader should verify this.
One popular way to input a series of values is to use the stream-extraction operation in the loop-continuation condition of a while loop. The extraction returns false
(0) when end-of-file is encountered. Consider the program of Fig. 11.11 which finds the highest grade on an exam. Assume the number of grades is not known in advance and that the user will type end-of-file to indicate that all the grades have been entered. The while condition, (cin >> grade ), becomes 0 (interpreted as false) when the user enters end-of- file.
In Fig. 11.11, cin >> grade can be used as a condition because the base class ios (from which istream is inherited) provides an overloaded cast operator that converts a stream into a pointer of type void *. The value of the pointer is 0 if an error occurred while
attempting to read a value or the end-of-file indicator was encountered. The compiler is able to use the void * cast operator implicitly.
11.4.2 get and getline Member Functions
The get member function with no arguments inputs one character from the designated stream (even if this is whitespace) and returns this character as the value of the function call. This version of get returns EOF when end-of-file on the stream is encountered.
Figure 11.12 demonstrates the use of member functions eof and get on input stream cin and member function put on output stream cout. The program first prints the value of cin.eof(), i.e., false (0 on the output) to show that end-of-file has not occurred on cin. The user enters a line of text and presses Enter followed by end-of-file (<ctrl>-z on IBM PC-compatible systems, <ctrl>-d on
UNIX and Macintosh systems). The program reads each character and outputs it to cout using member function put. When the end-of-file is encountered, the while ends and cin.eof()--now true--is printed again (1 on the output) to show that end-of-file has been set on cin. Note that this program uses the version of istream member function get that takes no arguments and returns the character being input.
The get member function with a character argument inputs the next character from the input stream (even if this is a whitespace character) and stores it in the character argument. This version of get returns 0 when end-of-file is encountered; otherwise this version of get
returns a reference to the istream object for which the get member function is being invoked.
A third version of the get member function takes three arguments--a character array, a size limit, and a delimiter (with default value '\n'). This version reads characters from the input stream. It reads up to one less than the specified maximum number of characters and terminates, or terminates as soon as the delimiter is read. A null character is inserted to terminate the input string in the character array used as a buffer by the program. The delimiter is not placed in the character array, but does remain in the input stream (the delimiter will be the next character read). Thus, the result of a
second consecutive get is an empty line unless the delimiter character is flushed from the input stream. Figure 11.13 compares input using cin with stream extraction (which reads characters until a whitespace character is encountered) and input with cin.get. Note that the call to cin.get does not specify a delimiter character, so the default '\n' is used.
The getline member function operates like the third version of the get member function and inserts a null character after the line in the character array. The getline function removes the delimiter from the stream (i.e., reads the character and discards it), but does not store it in the character array. The program of
Fig. 11.14 demonstrates the use of the getline member function to input a line of text.
Select the statement that generates a syntax error.
char c = cin.get();.
cin.getline( charArray, 88 );.
cin >> charArray;.
char c[255] = cin.get();.
and ignore 11.4.3 istream Member Functions peek, putback and ignore
The ignore member function skips over a designated number of characters (default is one character) or terminates upon encountering a designated delimiter (the default delimiter is EOF which causes ignore to skip to the end of file when reading from a file).
The putback member function places the previous character obtained by a get on an input stream back onto that stream. This function is useful for applications that scan an input stream looking for a field beginning with a specific character. When that character is input, the application puts that character back on the stream so
the character can be included in the data about to be input.
The peek member function returns the next character from an input stream, but does not remove the character from the stream.
11.4.4 Type-Safe I/O
C++ offers type-safe I/O. The << and >> operators are overloaded to accept data items of specific types. If unexpected data is processed, various error flags are set which the user may test to determine if an I/O operation succeeded or failed. In this manner the program "stays in control." We discuss these error flags in Section 11.8.
11.5 Unformatted I/O with read, gcount and write
Unformatted input/output is performed with the read and write member functions. Each of these inputs or outputs some number of bytes to or from a character array in memory. These bytes are not formatted in any way. They are simply input or output as raw bytes. For example, the call

char buffer[] = "HAPPY BIRTHDAY";

cout.write( buffer, 10 );

outputs the first 10 bytes of buffer (including null characters that would cause output with cout and << to
terminate). Since a character string evaluates to the address of its first character, the call

cout.write( "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 10 );

displays the first 10 characters of the alphabet.
The read member function inputs into a character array a designated number of characters. If fewer than the designated number of characters are read, failbit is set. We will soon see how to determine if failbit has been set (see Section 11.8).
The gcount member function reports the number of characters read by the last input operation.
Figure 11.15 demonstrates istream member functions read and gcount and ostream member function write.
The program inputs 20 characters (from a longer input sequence) into character array buffer with read, determines the number of characters input with gcount, and outputs the characters in buffer with write.
Select the statement that generates a syntax error.
cout.write( charArray, 78 );.
cout.read( charArray );.
cin.read( charArray, 100 );.
cout.write( "hello", 3 );.
11.6 Stream Manipulators
C++ provides various stream manipulators that perform formatting tasks. The stream manipulators provide capabilities such as setting field widths, setting precisions, setting and unsetting format flags, setting the fill character in fields, flushing streams, inserting a newline in the output stream and flushing the stream, inserting a null character in the output stream, and skipping whitespace in the input stream. These features are described in the following sections.
setbase 11.6.1 Integral Stream Base: dec, oct, hex and setbase
Integers are normally interpreted as decimal (base 10) values. To change the base in which integers are interpreted on a stream, insert the manipulator hex to set the base to hexadecimal (base 16) or insert the manipulator oct to set the base to octal (base 8). Insert the dec stream manipulator to reset the stream base to decimal.
The base of a stream may also be changed by the stream manipulator setbase which takes one integer argument of 10, 8, or 16 to set the base. Because setbase takes an argument, it is called a parameterized stream
manipulator. Using setbase or any other parameterized manipulator requires the inclusion of the <iomanip.h> header file. The stream base remains the same until it is explicitly changed. Figure 11.16 shows the use of the hex, oct, dec, and setbase stream manipulators.
setprecision) 11.6.2 Floating-Point Precision (precision, setprecision)
We can control the precision of floating-point numbers, i.e., the number of digits to the right of the decimal point, by using either the setprecision stream manipulator or the precision member function. A call to either of these sets the precision for all subsequent output operations until the next precision-setting call. The precision member function with no argument returns the current precision setting. The program of Fig. 11.17 uses both the precision member function and the setprecision manipulator to print a table showing
the square root of 2 with precisions varying from 0 through 9.
Select the statement that generates a syntax error.
cout << bin << 1988; // output binary.
cout << oct << 1987; // output octal.
cout << hex << 1986; // output hexadecimal.
cout << setprecision( 3 ) << 8.22;.
11.6.3 Field Width (setw, width)
The ios width member function sets the field width (i.e., the number of character positions in which a value should be output or the number of characters that should be input) and returns the previous width. If values processed are smaller than the field width, fill characters are inserted as padding. A value wider than the designated width will not be truncated--the full number will be printed.
Figure 11.18 demonstrates the use of the width member function on both input and output. Note that on input, a maximum of one fewer characters than the width will be read because provision is made for the
null character to be placed in the input string. Remember that stream extraction terminates when nonleading whitespace is encountered. The setw stream manipulator also may be used to set the field width. Note: When the user is prompted for input, the user should enter a line of text and press Enter followed by end-of-file (<ctrl>-z on IBM PC-compatible systems, <ctrl>-d on UNIX and Macintosh systems).
Select the statement that generates a syntax error.
cout << setw( 5 ) << x;.
cout.width( 8 );.
cout.setFieldWidth( 10 );.
11.6.4 User-Defined Manipulators
Users may create their own stream manipulators. Figure 11.19 shows the creation and use of new stream manipulators bell, ret (carriage return), tab, and endLine. Users may also create their own parameterized stream manipulators--consult your installation's manuals for instructions on how to do this.
11.7 Stream Format States
Various format flags specify the kinds of formatting to be performed during stream I/O operations. The setf, unsetf, and flags member functions control the flag settings.
11.7.1 Format State Flags
Each of the format state flags shown in Fig. 11.20 (and some that are not shown) is defined as an enumeration in class ios and is explained in the next several sections.
These flags can be controlled by the flags, setf, and unsetf member functions, but many C++ programmers prefer to use stream manipulators (see Section 11.7.8). The programmer may use the bitwise-or operation, |, to combine various options into a single long value (see Fig. 11.23). Calling the flags member function for a stream and specifying these "or-ed" options sets the options on that stream and returns a long value containing the prior options. This value is often saved
so that flags may be called with this saved value to restore the previous stream options.
The flags function must specify a value representing the settings of all the flags. The one-argument setf function, on the other hand, specifies one or more "or-ed" flags and "ors" them with the existing flag settings to form a new format state.
The setiosflags parameterized stream manipulator performs the same functions as the setf member function. The resetiosflags stream manipulator performs the same functions as the unsetf member function. To use either of these stream manipulators, be sure to #include <iomanip.h>.
The skipws flag indicates that >> should skip whitespace on an input stream. The default behavior of >> is to skip whitespace. To change this, use the call unsetf(ios::skipws). The ws stream manipulator also may be used to specify that whitespace should be skipped.
Select the statement that generates a syntax error.
cout.setf( ios::fixed );.
cout.unsetf( ios::showpoint, ios::left );.
cout.setf( ios::all );.
cout.setf( ios::dec );.
cout.unsetf( ios::right, ios::hex );.
cout.setf( ios::scientific );.
(ios::showpoint) 11.7.2 Trailing Zeros and Decimal Points (ios::showpoint)
The showpoint flag is set to force a floating-point number to be output with its decimal point and trailing zeros. A floating-point value of 79.0 will print as 79 without showpoint set and as 79.000000 (or as many trailing zeros as are specified by the current precision) with showpoint set. The program in Fig. 11.21 shows the use of the setf member function to set the showpoint flag to control trailing zeros and the printing of the decimal point for floating-point values.
ios::internal) 11.7.3 Justification (ios::left, ios::right, ios::internal)
The left and right flags enable fields to be left-justified with padding characters to the right, or right-justified with padding characters to the left, respectively. The character to be used for padding is specified by the fill member function or the setfill parameterized stream manipulator (see Section 11.7.4). Figure 11.22 shows the use of the setw, setiosflags, and resetiosflags manipulators and the setf and unsetf member functions to control the left- and right-justification of integer data in a field.
The internal flag indicates that a number's sign (or base when the ios::showbase flag is set; see Section 11.7.5) should be left-justified within a field, the number's magnitude should be right-justified, and intervening spaces should be padded with the fill character. The left, right, and internal flags are contained in static data member ios::adjustfield. The ios::adjustfield argument must be provided as the second argument to setf when setting the left, right, or internal justification flags. This enables setf to ensure that only one of the three justification flags is set (they are mutually exclusive). Figure 11.23 shows the use of the setiosflags and setw stream manipulators to specify
internal spacing. Note the use of the ios::showpos flag to force the printing of the plus sign.
11.7.4 Padding (fill, setfill)
The fill member function specifies the fill character to be used with adjusted fields; if no value is specified, spaces are used for padding. The fill function returns the prior padding character. The setfill manipulator also sets the padding character. Figure 11.24 demonstrates the use of the fill member function and the setfill manipulator to control the setting and resetting of the fill character.
Select the statement that produces the output:

*********************z.
cout << setw( 21 ) << z;.
cout << setprecision( 22 ) << "**" << z;.
cout << setw( 22 ) << setfill( '*' ) << 'z';.
cout << setw( 22 ) << z;.
cout << setfill('z') << setw( 22 ) << '*';.
cout << setiosflags( ios::internal ) << z;.
ios::hex, ios::showbase) 11.7.5 Integral Stream Base (ios::dec, ios::oct, ios::hex, ios::showbase)
The ios::basefield static member (used similarly to ios::adjustfield with setf) includes the ios::oct, ios::hex, and ios::dec flag bits to specify that integers are to be treated as octal, hexadecimal, and decimal values, respectively. Stream insertions default to decimal if none of these bits is set. The default for stream extractions is to process the data in the form in which it is supplied--integers starting with 0 are treated as octal values, integers starting with 0x or 0X are treated as hexadecimal values, and all other integers are treated as decimal values. Once a particular base is
specified for a stream, all integers on that stream are processed with that base until a new base is specified or until the end of the program.
Set the showbase flag to force the base of an integral value to be output. Decimal numbers are output normally, octal numbers are output with a leading 0, and hexadecimal numbers are output with either a leading 0x or a leading 0X (the uppercase flag determines which option is chosen; see Section 11.7.7). Figure 11.25 demonstrates the use of the showbase flag to force an integer to print in decimal, octal, and hexadecimal formats.
(ios::scientific, ios::fixed) 11.7.6 Floating-Point Numbers; Scientific Notation (ios::scientific, ios::fixed)
The ios::scientific flag and the ios::fixed flag are contained in the static data member ios::floatfield (used similarly to ios::adjustfield and ios::basefield in setf). These flags are used to control the output format of floating-point numbers. The scientific flag is set to force the output of a floating-point number in scientific format. The fixed flag forces a floating-point number to display a specific number of digits (as specified by the precision member function) to the right of the decimal point. Without these flags set, the value of the floating- point number determines the output format.
The call cout.setf(0, ios::floatfield) restores the system default format for outputting floating-point numbers. Figure 11.26 demonstrates the display of floating-point numbers in fixed and scientific formats using the two argument setf with ios::floatfield.
(ios::uppercase) 11.7.7 Uppercase/Lowercase Control (ios::uppercase)
The ios::uppercase flag is set to force an uppercase X or E to be output with hexadecimal integers or with scientific notation floating-point values, respectively (Fig. 11.27). When set, the ios::uppercase flag causes all letters in a hexadecimal value to be uppercase.
Select the statement that could produce the output:

9.99E+04.
cout << setiosflags( ios::fixed ) << 99900;.
cout << setiosflags(ios::uppercase) << 9.99e4;.
cout << hex << 9.99e4 << endl;.
cout << setiosflags(ios::showpoint) << 9.9E4;.
cout << setiosflags(ios::showpos) << 9.99E4;.
cout << setiosflags(ios::internal) << 99900;.
(flags, setiosflags, resetiosflags) 11.7.8 Setting and Resetting the Format Flags (flags, setiosflags, resetiosflags)
The flags member function without an argument simply returns (as a long value) the current settings of the format flags. The flags member function with a long argument sets the format flags as specified by the argument and returns the prior flag settings. Any format flags not specified in the argument to flags are reset. Note that the initial settings of the flags on each system may differ. The program of Fig. 11.28 demonstrates the use of the flags member function to set a new format state and save the previous format state, then restore the original format settings.
The setf member function sets the format flags provided in its argument and returns the previous flag settings as a long value as in

long previousFlagSettings = 

cout.setf( ios::showpoint | ios::showpos );

The setf member function with two long arguments as in

cout.setf( ios::left, ios::adjustfield );

first clears the bits of ios::adjustfield and then sets the ios::left flag. This version of setf is used with the bit fields associated with ios::basefield (represented by ios::dec, ios::oct, and ios::hex), ios::floatfield
(represented by ios::scientific and ios::fixed), and ios::adjustfield (represented by ios::left, ios::right, and ios::internal).
The unsetf member function resets the designated flags and returns the value of the flags prior to being reset.
11.8 Stream Error States
The state of a stream may be tested through bits in class ios--the base class for the classes istream, ostream, and iostream we are using for I/O.
The eofbit is set automatically for an input stream when end-of-file is encountered. A program can use the eof member function to determine if end-of-file has been encountered on a stream. The call

cin.eof()

returns true if end-of-file has been encountered on cin, and false otherwise.
The failbit is set for a stream when a format error occurs on the stream, but characters have not been lost. The fail member function determines if a stream operation has failed; it is normally possible to recover from such errors.
The badbit is set for a stream when an error occurs that results in the loss of data. The bad member function determines if a stream operation has failed. Such serious failures are normally nonrecoverable.
The goodbit is set for a stream if none of the bits eofbit, failbit, or badbit are set for the stream.
The good member function returns true if the bad, fail and eof functions would all return false. I/O operations should only be performed on "good" streams.
The rdstate member function returns the error state of the stream. A call to cout.rdstate, for example, would return the state of the stream which could then be tested by a switch statement that examines ios::eofbit, ios::badbit, ios::failbit, and ios::goodbit. The preferred means of testing the state of a stream is to use the member functions eof, bad, fail, and good--using these functions does not require the programmer to be familiar with particular status bits.
The clear member function is normally used to restore a stream's state to "good" so that I/O may proceed on that stream. The default argument for clear is ios::goodbit, so the statement

cin.clear();

clears cin and sets goodbit for the stream. The statement

cin.clear(ios::failbit)

actually sets the failbit. The user might want to do this when performing input on cin with a user-defined type and encountering a problem. The name clear seems inappropriate in this context, but it is correct.
The program of Fig. 11.29 illustrates the use of the rdstate, eof, fail, bad, good, and clear member functions.
The operator! member function returns true if either the badbit is set, the failbit is set, or both are set. The operator void* member function returns false if either the badbit is set, the failbit is set, or both are set. These functions are useful in file processing when a true/false condition is being tested in the condition of a selection structure or repetition structure.
Drag the correct term to the box associated with the member function:

Returns the error state of a stream.
Determines if a stream operation has failed.
Returns true, if fail, eof, and bad all return false.
Determines if end of file has been reached.
Restores a stream's state to good.
Determines if the stream operation has failed.
11.9 Tying an Output Stream to an Input Stream
Interactive applications generally involve an istream for input and an ostream for output. When a prompting message appears on the screen, the user responds by entering the appropriate data. Obviously, the prompt needs to appear before the input operation proceeds. With output buffering, outputs appear only when the buffer fills, when outputs are flushed explicitly by the program or automatically at the end of the program. C++ provides member function tie to synchronize (i.e., "tie together") the operation of an istream and an
ostream to ensure that outputs appear before their subsequent inputs. The call

cin.tie( &cout );

ties cout (an ostream) to cin (an istream). Actually, this particular call is redundant because C++ performs this operation automatically to create a user's standard input/output environment. The user would, however, explicitly tie together other istream/ostream pairs. To untie an input stream, inputStream, from an output stream, use the call

inputStream.tie( 0 );

11.10 Summary
* I/O operations are performed in a manner sensitive to the type of the data. * C++ I/O occurs in streams of bytes. A stream is simply a sequence of bytes. * I/O mechanisms of the system move bytes from devices to memory and vice versa in an efficient and reliable manner. * C++ provides "low-level" and "high-level" I/O capabilities. Low-level I/O-capabilities specify that some number of bytes should be transferred device-to-memory or memory-to-device. High-level I/O is performed
* with bytes grouped into meaningful units such as integers, floats, characters, strings and user-defined types. * C++ provides both unformatted I/O and formatted I/ O operations. Unformatted I/O transfers are fast, but process raw data that is difficult for people to use. Formatted I/O processes data in meaningful units, but requires extra processing time that can negatively impact high-volume data transfers. * Most C++ programs include the <iostream.h> header file that contains basic information required for all stream I/O operations. * The <iomanip.h> header contains information for formatted input/output with parameterized stream * manipulators. * The <fstream.h> header contains information for file processing operations. * The istream class supports stream input operations. * The ostream class supports stream output operations. * The iostream class supports both stream-input and stream-output operations. * The istream class and the ostream class are each derived through single inheritance from the ios base class. * The iostream class is derived through multiple inheritance from both the istream class and the ostream * class. * The left shift operator (<<) is overloaded to designate stream output and is referred to as the stream-insertion operator. * The right shift operator (>>) is overloaded to designate stream input and is referred to as the stream-extraction operator. * The istream object cin is tied to the standard input device, normally the keyboard. * The ostream class object cout is tied to the standard output device, normally the display screen. * The ostream class object cerr is tied to the standard error device. Outputs to cerr are unbuffered; each * insertion to cerr appears immediately. * Stream manipulator endl issues a newline character and flushes the output buffer. * The C++ compiler determines data types automatically for input and output. * Addresses are displayed in hexadecimal format by default. * To print the address in a pointer variable, cast the pointer to void*. * Member function put outputs one character. Calls to put may be cascaded. * Stream input is performed with the stream-extraction operator >>. This operator automatically skips * whitespace characters in the input stream. * The >> operator returns false when end-of-file is encountered on a stream. * Stream extraction causes failbit to be set for improper input, and badbit to be set if the operation fails. * A series of values can be input using the stream- extraction operation in a while loop header. The extraction returns 0 when end-of-file is encountered. * The get member function with no arguments inputs one character and returns the character; EOF is returned if end-of-file is encountered on the stream. * The get member function with an argument of type * char inputs one character. EOF is returned when end- of-file is encountered; otherwise, the istream object for which the get member function is being invoked is returned. * The get member function with three arguments--a character array, a size limit, and a delimiter (with default value newline)--reads characters from the input stream up to a maximum of limit - 1 characters and terminates, or terminates when the delimiter is read. The input string is terminated with a null character. The delimiter is not placed in the character array, but remains in the input stream. * The getline member function operates like the three * argument get member function. The getline function removes the delimiter from the input stream, but does not store it in the string. * Member function ignore skips the specified number of characters (default is one character) in the input stream; it terminates if the specified delimiter is encountered (the default delimiter is EOF). * The putback member function places the previous character obtained by a get on a stream back onto that stream. * The peek member function returns the next character from an input stream, but does not remove the character from the stream. * C++ offers type-safe input/output. If unexpected data is processed by the << and >> operators, various error flags are set which the user may test to determine if an I/O operation succeeded or failed. * Unformatted I/O is performed with member functions read and write. These input or output some number of bytes to or from memory beginning at a designated memory address. They are input or output as raw bytes with no formatting. * The gcount member function returns the number of characters input by the previous read operation on that stream. * Member function read inputs a specified number of * characters into a character array. failbit is set if fewer than the specified number of characters are read. * To change the base in which integers output, use the manipulator hex to set the base to hexadecimal (base 16) or oct to set the base to octal (base 8). Use manipulator dec to reset the base to decimal. The base remains the same until explicitly changed. * The parameterized stream manipulator setbase also sets the base for integer output. setbase takes one integer argument of 10, 8, or 16 to set the base. * Floating-point precision can be controlled using either the setprecision stream manipulator or the precision member function. Both set the precision for all * subsequent output operations until the next precision- setting call. The precision member function with no argument returns the current precision value. * Parameterized manipulators require the inclusion of the <iomanip.h> header file. * Member function width sets the field width and returns the previous width. Values smaller than the field are padded with fill characters. The field width setting applies only for the next insertion or extraction; the field width is implicitly set to 0 afterward (subsequent values will be output as large as they need to be). Values larger than a field are printed in their entirety. Function width with no argument returns the current width * setting. Manipulator setw also sets the width. * For input, the setw stream manipulator establishes a maximum string size; if a larger string is entered, the larger line is broken into pieces no larger than the designated size. * Users may create their own stream manipulators. * Member functions setf, unsetf, and flags control the flag settings. * The skipws flag indicates that >> should skip whitespace on an input stream. The ws stream manipulator also skips over leading whitespace in an input stream.
* Format flags are defined as an enumeration in class ios. * Format flags are controlled by the flags and setf member functions, but many C++ programmers prefer to use stream manipulators. The bitwise-or operation, |, can be used to combine various options into a single long value. Calling the flags member function for a stream and specifying these "or-ed" options sets the options on that stream and returns a long value containing the prior options. This value is often saved so flags may be called with this saved value to restore the previous stream options. * The flags function must specify a value representing * the total settings of all the flags. The setf function with one argument, on the other hand, automatically "ors" the specified flags with the existing flag settings to form a new format state. * The showpoint flag is set to force a floating-point number to be output with a decimal point and number of significant digits specified by the precision. * The left and right flags cause fields to be left-justified with padding characters to the right, or right-justified with padding characters to the left. * The internal flag indicates that a number's sign (or base when the flag ios::showbase is set) should be left- justified within a field, magnitude should be right-justi * fied, and intervening spaces should be padded with the fill character. * ios::adjustfield contains the flags left, right, and internal. * Member function fill specifies the fill character to be used with left, right, and internal adjusted fields (space is the default); the prior padding character is returned. Stream manipulator setfill also sets the fill character. * Static member ios::basefield includes the oct, hex, and dec bits to specify that integers are to be treated as octal, hexadecimal, and decimal values, respectively. Integer output defaults to decimal if none of these bits * is set; stream extractions process the data in the form in which it is supplied. * Set the showbase flag to force the base of an integral value to be output. * Static data member ios::floatfield contains the flags scientific and the fixed. Set the scientific flag to output a floating-point number in scientific format. Set the fixed flag to output a floating-point number with the precision specified by the precision member function. * The call cout.setf(0, ios::floatfield) restores the default format for displaying floating-point numbers. * Set the uppercase flag to force an uppercase X or E to be output with hexadecimal integers or with scien * tific notation floating-point values, respectively. When set, the ios::uppercase flag causes all letters in a hexadecimal value to be uppercase. * Member function flags with no argument returns the long value of the current settings of the format flags. Member function flags with a long argument sets the format flags specified by the argument and returns the prior flag settings. * Member function setf sets the format flags in its argument and returns the previous flag settings as a long value. * Member function setf(long setBits, long resetBits) clears the bits of the resetBits, then sets the bit in set * Bits. * Member function unsetf resets the designated flags and returns the value of the flags prior to being reset. * Parameterized stream manipulator setiosflags performs the same functions as member function flags. * Parameterized stream manipulator resetiosflags performs the same functions as member function unsetf. * The state of a stream may be tested through bits in class ios. * The eofbit is set for an input stream when end-of-file is encountered during an input operation. The eof member function is used to determine if the eofbit has been set. * The failbit is set for a stream when a format error occurred on the stream, but characters have not been lost. The fail member function determines if a stream operation has failed; it is normally possible to recover from such errors. * The badbit is set for a stream when an error occurred that resulted in the loss of data. The bad member function determines if a stream operation has failed. Such serious failures are normally nonrecoverable. * The good member function returns true if the bad, fail, and eof functions would all return false. I/O operations should only be performed on "good" streams. * The rdstate member function returns the error state * of the stream. * Member function clear is normally used to restore a stream's state to "good" so that I/O may proceed on that stream. * C++ provides the tie member function to synchronize istream and ostream operations to ensure that outputs appear before subsequent inputs.
This chapter does not contain any Testing and Debugging tips.
This chapter does not contain any Applet Examples.